<?php
namespace app\bancard\controller;
use app\bancard\model\DeviceAssociation;
use app\bancard\model\ExaminationMode;
use think\facade\Cache;
use app\bancard\model\DeviceTemplateType;
class Device extends Common {
	
	//首页
	public function index(){
		
		return $this->fetch();
	}
	
	public function lists(){
		$data = request()->param();
		
		$limit = isset($data['limit'])?$data['limit']:10;
		$offset = isset($data['offset'])?$data['offset']:1;
		$keywords = isset($data['keywords'])?$data['keywords']:'';
		//获取设备信息列表;
		$this->devices = $this->devices($offset,$limit,$keywords);
		
		//获取设备ids;
		$ids = array_column($this->devices['data'],'id');
		
		$Alldevices = db('device_association')
					  ->alias('a')
					  ->leftJoin('setting_switch b','a.switch_id = b.id')
					  ->leftJoin('screen_saver c','a.screen_saver_id = c.id')
					  ->leftJoin('setup_countdown d','a.countdown_id = d.id')
					  ->whereIn('a.device_id',$ids)
					  ->column('a.*,b.start_time,b.end_time,c.title,c.type,d.title as countdown_name ', 'a.device_id');
//        p($Alldevices);die;
		//获取班级ids
		$class_ids = array_filter(array_column($Alldevices,'class_id'));

		//得到班级信息
		$class_info = $this->getNameById($class_ids);
		// p($class_info);die;
		$result = $this->devices['data'];
		//通过模板ids查询出所有设备对应的模板的信息
		$template_result = DeviceTemplateType::with('template')->whereIn('d_ass_id', $ids)->select();
		//通过ids查询出所有设备对应的考试模式的所有信息
//        p($ids);die;
		$templates = [];
		foreach($template_result as $key=>$val) {
			if($val['template']) {
				$templates[$val['d_ass_id']][] = [
					'type' => $val['type'],
					'title' => $val['template']['title'],
					'id' => $val['template']['id'],
				];
			}
		}

		foreach($result as $k=>$v){
			if(isset($Alldevices[$v['id']])){
				$value = $Alldevices[$v['id']];
				if(isset($value['class_id']) && isset($class_info[$value['class_id']])){
					$result[$k]['class_name'] = $class_info[$value['class_id']];
				}else{
					$result[$k]['class_name'] = "";
				}
                if(isset($value['countdown_id'])){
                    $result[$k]['countdown_name'] = $value['countdown_name'];
                    $result[$k]['countdown_id'] = $value['countdown_id'];
                }else{
                    $result[$k]['countdown_id'] = "";
                    $result[$k]['countdown_name'] = "";
                }
				$result[$k]['d_id'] = $value['id'];
				$result[$k]['class_id'] = $value['class_id'];
				
				$result[$k]['room_id'] = $value['room_id'];
				$result[$k]['screen_saver_id'] = $value['screen_saver_id'];
				$result[$k]['screen_type'] = $value['type'];
				$result[$k]['countdown_id'] = $value['countdown_id'];
				$result[$k]['switch_id'] = $value['switch_id'];
				$result[$k]['end_time'] = $value['end_time'];
				$result[$k]['start_time'] = $value['start_time'];
				$result[$k]['title'] = $value['title'];
				$result[$k]['status'] = 1;
			}else{
				$result[$k]['d_id'] = "";
				$result[$k]['class_id'] = "";
				$result[$k]['room_id'] = "";
				$result[$k]['screen_saver_id'] = "";
				$result[$k]['screen_type'] = "";
				$result[$k]['countdown_id'] = "";
				$result[$k]['switch_id'] ="";
				$result[$k]['end_time'] ="";
				$result[$k]['start_time'] = "";
				$result[$k]['title'] = "";
				$result[$k]['status'] = 0;
			}
			
			if (isset($templates[$v['id']])) {
				$result[$k]['templates'] = $templates[$v['id']];
			}else{
                $result[$k]['templates'] = [];
            }
		}

		return showTable(0, 'OK', $this->devices['total'] ,$result, 200);
	}
	//解绑设备
	public function untyingDevice(){
		$data = request()->param();
		$result = db('device_association')->delete($data['ids']);
		if($result){
			$this->reset($data['ids']);
			return showTable(0, 'OK', 1 ,"", 200);
		}else{
			return showTable(1, 'OK', 0 ,"", 200);
		}
		
	}
	//绑定班级屏保开关机模板
	public function seting(){
		$data = request()->param();
		if($this->request->isPost()){
			$id = db('device_association')->where(['class_id'=>$data['class_id']])->field('id')->find();
			//存在就修改
			$ndata = [
				'device_id'=>$data['device_id'],
				'class_id'=>$data['class_id'],
				'screen_saver_id'=>$data['screen_saver_id'],
				'switch_id'=>$data['switch_id']
			];
			if($id){
				// p($id);die;
				$result = db('device_association')->where(['id'=>$id['id']])->data($ndata)->update();
				return showTable(0, '修改成功', 1 ,$result, 200);
			}else{
				
				$ids = db('device_template_type')->where(['d_ass_id',$data['device_id']])->field('id')->column('id','type');
				$tmp_data = [
					[
						'd_ass_id'=>$data['device_id'],
						'template_id'=>$data['horizontal_id'],
						'type'=>1
					],
					[
						'd_ass_id'=>$data['device_id'],
						'template_id'=>$data['vertical_id'],
						'type'=>2
					]
				];
				db('device_template_type')->insertAll($tmp_data);
			}
		}
		//屏保
		if($data['title'] == 'null') $data['title'] = "";
		$this->assign('screen_saver_id',$data['screen_saver_id']);
		$this->assign('title',$data['title']);
		$this->assign('screen_type',$data['screen_type']);
		
		//绑定班级
		if($data['device'] == 'null') $data['device'] = "";
		$this->assign('device',$data['device']);
		$this->assign('device_id',$data['id']);
		// 模板
		$tpl_ids = db('device_association')->alias('a')->join('device_template_type b','a.id=b.d_ass_id')->where(['a.device_id'=>$data['id']])->column("b.template_id");
		$horizontal = [];
		$vertical = [];
		if(!empty($tpl_ids)){
			$tpl = db('class_plate_template')->whereIn('id',$tpl_ids)->field('title,id,type')->select();
			foreach($tpl as $k=>$v){
				if($v['type'] == 1){
					$horizontal = $v;
				}else{
					$vertical = $v;
				}
			}
		}
		$this->assign('horizontal',$horizontal);
		$this->assign('vertical',$vertical);
		//开关机
		if($data['switch_id']){
			$switch = db('setting_switch')->where(['id'=>$data['switch_id']])->field('id,title')->find();
			$this->assign('switch',$switch);
		}
		//班级信息
		if($data['class_id']){
			$class_info = $this->class_info_id($data['class_id']);
			// p($class_info);die;
			$this->assign('classInfo',$class_info);
		}
		
		$this->assign('key',$data['key']);
		return $this->fetch();
	}
	//班级信息
	public function class_info(){
		if($this->request->isPost()){
			$data = request()->param();
			$result = db('device_association')->where(['class_id'=>$data['basicData']])->find();

			if($result){
				return showTable(1, '该班级已经绑定，请先解绑', 0 , "该班级已经绑定，请先解绑" , 200);
			}else{
				
				$device = db('device_association')->where(['device_id'=>$data['device_ids'][0]])->find();
				if($device){
					$db = [
						'class_id' =>$data['basicData'],
						'device_key'=>$data['device_key']
					];
					$c = db('device_association')->where(['id'=>$device['id']])->update($db);
					return showTable(0, 'OK', 0 , $c , 200);
				}else{
					$db = [
						'class_id' =>$data['basicData'],
						'device_id' =>$data['device_ids'][0],
						'user_id' => session('admin.id'),
						'device_key'=>$data['device_key']
					];
					$c = db('device_association')->insert($db);
					return showTable(0, 'OK', 0 , $c , 200);
				}				
			}
		}
		$getClass = $this->getClass();
		$this->assign('getClass', json_encode($getClass['data']));
		return $this->fetch();
	}
	//横版
	public function temp_h_all(){
		$data = request()->param();
		if($this->request->isPost()){
			$limit =isset($data['limit'])?$data['limit']:12;
			$offset =isset($data['offset'])?$data['offset']:1;
			$start = ($offset-1)*$limit;
			$map =[
				'type'=>$data['type'],
				'user_id' => session('admin.id'),
				'school_id' => session('schoolInfo.id'),
                'show'=>1
			];
			$count = db('class_plate_template')->where($map)->count();
			$result = db('class_plate_template')->where($map)->limit($start,$limit)->order('id desc,sort desc')->field('id,title,created_at,describe,image,type,show,istop,sort')->select();
			return showTable(0, 'OK', $count ,$result, 200);
		}
		return $this->fetch();
	}
	//竖版
	public function temp_v_all(){
		$data = request()->param();
		if($this->request->isPost()){
			$limit =isset($data['limit'])?$data['limit']:12;
			$offset =isset($data['offset'])?$data['offset']:1;
			$start = ($offset-1)*$limit;
			$map =[
				'type'=>$data['type'],
				'user_id' => session('admin.id'),
				'school_id' => session('schoolInfo.id'),
                'show'=>1
			];
			$count = db('class_plate_template')->where($map)->count();
			$result = db('class_plate_template')->cache('class_plate_template'.$limit.$offset.$data['type'],3600,'class_plate_template')->where($map)->limit($start,$limit)->order('id desc,sort desc')->field('id,title,created_at,describe,image,type,show,istop,sort')->select();
			return showTable(0, 'OK', $count ,$result, 200);
		}
		return $this->fetch();
	}
	//屏保
	public function screen_saver_all(){
		return $this->fetch();
	}
	//开关机
	public function switch_all(){
		$data = request()->param();
		if($this->request->isPost()){
			$limit =isset($data['limit'])?$data['limit']:12;
			$offset =isset($data['offset'])?$data['offset']:1;
			$start = ($offset-1)*$limit;
			$map =[
				'user_id'=>session('admin.id'),
				'school_id'=> session('schoolInfo.id')
			];
			$count = db('setting_switch')->where($map)->count();
			$result = db('setting_switch')->where($map)->limit($start,$limit)->order('sort desc,id desc')->select();
			return showTable(0, 'OK', $count ,$result, 200);
		}
		return $this->fetch();
	}
	//设置开关机
	public function push_switch(){

        $device_ids = $this->request->request('device_ids/a');
        $ids = $this->request->request('ids/a');//
        $switch_id = $this->request->request('id');
        if (!$device_ids) {
            return showTable(1, '没有选择设备', 0 , "" , 200);
        }

        DeviceAssociation::whereIn('id', $ids)->update([
            'switch_id' => $switch_id,
            'updated_at_switch'=>time()
        ]);

        $devices = DeviceAssociation::whereIn('id', $ids)->select()->toArray();
        $add_data_ids = array_diff($device_ids, array_column($devices, 'device_id'));

        $insert_data = [];
        foreach ($add_data_ids as $index => $add_data_id) {
            $insert_data[] = [
                'device_id' => $add_data_id,
                'switch_id' => $switch_id,
                'user_id' => session('admin.id')
            ];
        }

        $model = new DeviceAssociation();
        $model->saveAll($insert_data);
        $class_ids = array_filter(array_column($devices, 'class_id'));
        //推送key;
        $pushKey = [
            'action' => 'switch',
        ];
        $ret = $this->socketPush($class_ids,$pushKey);
        return showTable(0, 'OK', 0 , $ret , 200);
	}
	//设置屏保
	public function push_screen(){
        $device_ids = $this->request->request('device_ids/a');
        $ids = $this->request->request('ids/a');//
        $screen_saver_id = $this->request->request('id');
        if (!$device_ids) {
            return showTable(1, '没有选择设备', 0 , "" , 200);
        }

        DeviceAssociation::whereIn('id', $ids)->update([
            'screen_saver_id' => $screen_saver_id,
            'updated_at_screen'=>time()
        ]);

        $devices = DeviceAssociation::whereIn('id', $ids)->select()->toArray();
        $add_data_ids = array_diff($device_ids, array_column($devices, 'device_id'));

        $insert_data = [];
        foreach ($add_data_ids as $index => $add_data_id) {
            $insert_data[] = [
                'device_id' => $add_data_id,
                'screen_saver_id' => $screen_saver_id,
                'user_id' => session('admin.id')
            ];
        }

        $model = new DeviceAssociation();
        $model->saveAll($insert_data);
        $class_ids = array_filter(array_column($devices, 'class_id'));
        //推送key;
        $pushKey = [
            'action' => 'screen',
        ];
        $this->socketPush($class_ids,$pushKey);
        return showTable(0, 'OK', 0 , "" , 200);
	}
	//设置横竖版模板
	public function push_temp(){
        $device_ids = $this->request->request('device_ids/a');//选中设备ids
        $template_id = $this->request->request('id');//模板id
        $type = $this->request->request('type');//模板对应的类型
        //判断是否选择设备
        if (!$device_ids) {
            return showTable(1, '没有选择设备', 0 , "" , 200);
        }
        //如果查询到关联表有该设备的对应模板信息，修改模板
        DeviceTemplateType::whereIn('d_ass_id', $device_ids)->where(['type'=>$type])->update([
            'template_id' => $template_id
        ]);

        //查询出所有设备的信息
        $devices = DeviceTemplateType::whereIn('d_ass_id', $device_ids)->where(['type'=>$type])->select()->toArray();
        //求出需要添加的设备ids
        $add_data_ids = array_diff($device_ids, array_column($devices, 'd_ass_id'));
        $insert_data = [];
        foreach ($add_data_ids as $index => $add_data_id) {
            $insert_data[] = [
                'd_ass_id' => $add_data_id,
                'template_id' => $template_id,
                'user_id' => session('admin.id'),
                'type'=> $type
            ];
        }

        $model = new DeviceTemplateType();
        $model->saveAll($insert_data);
        $device_ids = array_unique(array_column($devices, 'd_ass_id'));
        //推送key;
        $pushKey = [
            'action' => 'temp',
        ];
        $this->socketPush_device($device_ids,$pushKey);
        return showTable(0, 'OK', 0 , "" , 200);
	}
	//编辑设备名称
	public function editDeviceName(){
        $data = request()->param();
	    $result = $this->editName($data['id'],$data['device']);
        if($result['code'] == 1){
            return showTable(0, 'OK', 0 , "" , 200);
        }
    }
	//配置考试模式
    public function exam_mode(){
        if($this->request->isPost()){
            $device_ids = $this->request->request('device_ids/a');
            $ids = $this->request->request('ids/a');
            $exam_id = $this->request->request('id');
            if (!$device_ids) {
                return showTable(1, '没有选择设备', 0 , "" , 200);
            }

            DeviceAssociation::whereIn('id', $ids)->update([
                'exam_id' => $exam_id
            ]);

            $devices = DeviceAssociation::whereIn('id', $ids)->select()->toArray();
            $add_data_ids = array_diff($device_ids, array_column($devices, 'device_id'));

            $insert_data = [];
            foreach ($add_data_ids as $index => $add_data_id) {
                $insert_data[] = [
                    'device_id' => $add_data_id,
                    'exam_id' => $exam_id,
                    'user_id' => session('admin.id')
                ];
            }

            $model = new DeviceAssociation();
            $model->saveAll($insert_data);
            $class_ids = array_filter(array_column($devices, 'class_id'));
            $pushKey = [
                'action' => 'exam',
            ];
            $this->socketPush($class_ids,$pushKey);
            return showTable(0, 'OK', 0 , "" , 200);
        }
        return $this->fetch();
    }
    //配置倒计时
    public function countdown(){
        if($this->request->isPost()){
            $device_ids = $this->request->request('device_ids/a');
            $ids = $this->request->request('ids/a');
            $countdown_id = $this->request->request('id');
            if (!$device_ids) {
                return showTable(1, '没有选择设备', 0 , "" , 200);
            }
            DeviceAssociation::whereIn('id', $ids)->update([
                'countdown_id' => $countdown_id
            ]);

            $devices = DeviceAssociation::whereIn('id', $ids)->select()->toArray();
            $add_data_ids = array_diff($device_ids, array_column($devices, 'device_id'));

            $insert_data = [];
            foreach ($add_data_ids as $index => $add_data_id) {
                $insert_data[] = [
                    'device_id' => $add_data_id,
                    'countdown_id' => $countdown_id,
                    'user_id' => session('admin.id')
                ];
            }

            $model = new DeviceAssociation();
            $model->saveAll($insert_data);
            $class_ids = array_filter(array_column($devices, 'class_id'));
            $pushKey = [
                'action' => 'refresh',
                'params' => 'countdown',
            ];
            $this->socketPush($class_ids,$pushKey);
            return showTable(0, 'OK', 0 , "" , 200);
        }
        return $this->fetch();
    }
    //更新人脸库
    public function updateFaces(){
        $device_ids = $this->request->request('device_ids/a');
        //推送key;
        $pushKey = [
            'action' => 'face',
        ];
        DeviceAssociation::whereIn('device_id', $device_ids)->update([
            'updated_at_face' => time()
        ]);
        $content = $this->socketPush_device($device_ids,$pushKey);
        if(!empty($content)){
            return showTable(0, 'OK', 0 , $content , 200);
        }else{
            return showTable(1, '同步失败稍后重试', 0 , "" , 200);
        }
    }
    //开启调试模式
    public function debug_true(){
        if($this->request->isPost()){
            $device_ids = $this->request->request('device_ids/a');
            $ids = $this->request->request('ids/a');
            if (!$device_ids) {
                return showTable(1, '没有选择设备', 0 , "" , 200);
            }
            $devices = DeviceAssociation::whereIn('id', $ids)->select()->toArray();
            $class_ids = array_filter(array_column($devices, 'class_id'));
            $pushKey = [
                'action' => 'debug_true',
            ];
            $this->socketPush_device($device_ids,$pushKey);
            return showTable(0, 'OK', 0 , "" , 200);
        }
    }
    //开启调试模式
    public function debug_false(){
        if($this->request->isPost()){
            $device_ids = $this->request->request('device_ids/a');
            $ids = $this->request->request('ids/a');
            if (!$device_ids) {
                return showTable(1, '没有选择设备', 0 , "" , 200);
            }
            $devices = DeviceAssociation::whereIn('id', $ids)->select()->toArray();
            $class_ids = array_filter(array_column($devices, 'class_id'));
            $pushKey = [
                'action' => 'debug_false',
            ];
            $this->socketPush_device($device_ids,$pushKey);

            return showTable(0, 'OK', 0 , $c , 200);
        }
    }
}